package com.yidushishizijie;


import java.util.ArrayList;
import java.util.List;

public class ThreadWaitNodifyDemo03 {
    public static void main(String[] args) {
        List list = new ArrayList();
        MyResources resource = new MyResources(list);

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    resource.provider();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    resource.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}

class MyResources{
    private List list;

    public MyResources(List list) {
        this.list = list;
    }

    public synchronized void provider() throws InterruptedException{
        //判断
        if(list.size() != 0){
            this.wait();
        }
        //操作
        Object object = new Object();
        list.add(object);
        System.out.println(Thread.currentThread().getName()+"\t"+object);

        //通知
        this.notifyAll();
    }

    public synchronized void consumer() throws InterruptedException{
        //判断
        if(list.size() == 0){
            this.wait();
        }
        //操作
        Object object = list.remove(0);
        System.out.println(Thread.currentThread().getName()+"\t"+object);

        //通知
        this.notifyAll();
    }
}
